<?php


namespace App\WebSocketController;


use App\Actor\ChatActor;
use App\Actor\ChatManager;
use App\Actor\Command;
use App\Model\ChatModel;
use EasySwoole\Actor\Exception\InvalidActor;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\EasySwoole\Task\TaskManager;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\RedisPool\RedisPool;
use EasySwoole\Socket\AbstractInterface\Controller;
use Throwable;

class Index extends Controller
{
    /**
     * @throws InvalidActor
     */
    public function onOpen()
    {
        $args = $this->caller()->getArgs();
        $userId = $args['userId'];
        $client = $this->caller()->getClient();
        $fd = $client->getFd();
        $info = ChatManager::chatInfo($userId);
        if ($info) {
            $command = new Command();
            $command->setCommand($command::WS_PING);
            $command->setFd($fd);
            ChatActor::client()->send($info->getActorId(), $command);
//            $this->response()->setMessage(['code' => 200, 'data' => [
//                'content' => 'ping'
//            ], 'msg' => 'success']);
        } else {
            ChatActor::client()->create([
                'fd' => $fd,
                'userId' => $userId
            ]);
        }


        //RedisPool::defer('redis')->set("user_" . $userId, $fd, 10);
    }

    /**
     * @throws Exception
     * @throws Throwable
     * @throws InvalidActor
     */
    public function send()
    {
        $args = $this->caller()->getArgs();
        $param = $args['param'];
        var_dump($param);
        $data = [
            'sid' => $param['msg']['userinfo']['sid'],
            'fid' => $param['sid'],
            'sendId' => $param['msg']['userinfo']['sid'],
            'receiveId' => $param['sid'],
            'type' => $param['type'],
            'send_type' => $param['msg']['type'],
            'content' => json_encode($param['msg']['content']),
            'is_read' => 1
        ];
        if ($data['sid'] == $data['fid']) {
            $param['msg']['content'] = [
                "text" => '自己无法给自己发送信息'
            ];
            $result = [
                'type' => 'system',
                'msg' => [
                    'id' => 1,
                    'time' => $param['msg']['time'],
                    'type' => 'text',
                    'userinfo' => [
                        'sid' => $data['sendId']
                    ],
                    'content' => $param['msg']['content']
                ]
            ];
        } elseif ($data['fid'] <= 0) {
            $param['msg']['content'] = [
                "text" => '系统暂无法回复信息，请致电客服!'
            ];
            $result = [
                'type' => 'system',
                'msg' => [
                    'id' => 1,
                    'time' => $param['msg']['time'],
                    'type' => 'text',
                    'userinfo' => [
                        'sid' => $data['fid']
                    ],
                    'content' => $param['msg']['content']
                ]
            ];
            $param['sid'] = $data['sid'];
        } else {
            $receiveData = [
                'sid' => $param['sid'],
                'fid' => $param['msg']['userinfo']['sid'],
                'sendId' => $param['msg']['userinfo']['sid'],
                'receiveId' => $param['sid'],
                'type' => $param['type'],
                'send_type' => $param['msg']['type'],
                'content' => json_encode($param['msg']['content'])
            ];
            $time = $param['msg']['time'];

            $chat = ChatModel::create()->addChat($data);
            $chat1 = ChatModel::create()->addChat($receiveData);


            $result = [
                'type' => $data['type'],
                'msg' => [
                    'id' => $chat,
                    'time' => $time,
                    'type' => $data['send_type'],
                    'userinfo' => [
                        'sid' => $data['sendId']
                    ],
                    'content' => json_decode($data['content'], true)
                ]
            ];
        }

        $info = ChatManager::chatInfo($param['sid']);
        if ($info) {
            $command = new Command();
            $command->setCommand($command::WS_MSG);
            $command->setParams($result);
            ChatActor::client()->send($info->getActorId(), $command);
        }
    }

    /**
     * @throws Throwable
     * @throws Exception
     * @throws InvalidActor
     */
    public function sendSys($param)
    {
        $receiveData = [
            'sid' => $param['sid'],
            'fid' => $param['msg']['userinfo']['sid'],
            'sendId' => $param['msg']['userinfo']['sid'],
            'receiveId' => $param['sid'],
            'type' => $param['type'],
            'send_type' => $param['msg']['type'],
            'content' => json_encode($param['msg']['content'])
        ];
        $time = $param['msg']['time'];

        $chat = ChatModel::create()->addChat($receiveData);


        $result = [
            'type' => $receiveData['type'],
            'msg' => [
                'id' => $chat,
                'time' => $time,
                'type' => $receiveData['send_type'],
                'userinfo' => [
                    'sid' => $receiveData['sendId']
                ],
                'content' => json_decode($receiveData['content'], true)
            ]
        ];

        $info = ChatManager::chatInfo($param['sid']);
        if ($info) {
            $command = new Command();
            $command->setCommand($command::WS_MSG);
            $command->setParams($result);
            ChatActor::client()->send($info->getActorId(), $command);
        }
    }

    public function index()
    {
        // 接受请求同时给返回请求
        $this->response()->setMessage('this is index');

        // 给某个人发送请求

        // 自己的链接对象 $client->getFd()获取自己的socket ID
        $client = $this->caller()->getClient();

        $args = $this->caller()->getArgs();

        $fd = $args['fd'];

        // 异步推送
        TaskManager::getInstance()->async(function () use ($fd) {
            // 获取websocket对象
            $server = ServerManager::getInstance()->getSwooleServer();

            //给指定客户推送消息，socket id可以使用redis存储;
            $server->push($fd, "asdasda");
        });

    }
}